/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-10 10:16:50
 * @filename : controller/total_gold.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){
        
    var name = 'Total Gold', mId = 'total_gold',
        highchartMC = require('{model}highchart'), 
        highcharts = require('highcharts'),
        tpl = require('{view}page_gold.tpl'),
        tplH = require('{view}head_gold.tpl'),
        tplT = require('{view}table.tpl'),
        tplS = require('{view}select.tpl');
      
    var highchartM = new highchartMC.highchartM;

    var tempOpt = {
             engine : '',
             begin_date : null,
             end_date : null,
             group : 'day'
        };
 
    var TotalGoldView = Backbone.View.extend({
    
        initialize: function (obj) { 
            this.run(obj);
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                $('#'+mId).find('.m_head').append(_.template(tplH));
                this.defaultOpt();
                this.afterBindEvt();
                this.fetchData(tempOpt); 
            } else {
                $('#'+mId).css('display','block');
            } 
        },

        afterBindEvt : function() {
             var tthis = this,dom = $('#'+mId);
             
             new Pikaday({
                    field: dom.find('.from_time')[0],
                    firstDay: 1,
                    minDate: new Date('1997-01-01'),
                    maxDate: new Date('2020-12-31'),
                    yearRange: [1997,2020]
             });
             
             new Pikaday({
                    field: dom.find('.to_time')[0],
                    firstDay: 1,
                    minDate: new Date('1997-01-01'),
                    maxDate: new Date('2020-12-31'),
                    yearRange: [1997,2020]
             });

            dom.find('.selectTime').on('change',function(){
                var val = $(this).val();
                    share.setInputDate(val,mId);
            });

            dom.find('.do').on('click',function(){
                var bool = share.getPostData(tempOpt,mId);
                if (bool) {
                     tthis.fetchData(tempOpt);
                }
            });

            dom.find('.m_head').find('input[type="text"]').on('focus',function(){
                $('#'+mId).find('.selectTime').find("option[value='']").attr("selected",true); 
            });

        },
     
        defaultOpt : function() {
             var dom = $('#'+mId);
             this.selectSite();
             share.setInputDate('last-week',mId);
             tempOpt.end_date = dom.find('.to_time').val();
             tempOpt.begin_date = dom.find('.from_time').val(); 
             tempOpt.group  = 'day';
             tempOpt.engine  = '';
        },
 
        selectSite : function() {
             var siteInfo =  share.getAllSites(1);
             $('#'+mId).find('.selectInfo').html(_.template(tplS)({obj:siteInfo}));
        },  

        fetchData : function(data) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+'total_gold',
                type : 'POST',
                data : data,
                success : function(data) {                  
                    tthis.fetchSuccess(data);
                },
                error : function(xhr, errorType, error) {},
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };
           
            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt,true);
        },

        fetchSuccess : function(data) {
            //add main gold
            _.each(data,function(obj) {
                obj.MAIN_GOLD = Number(obj.TOTAL_GOLD) - Number(obj.AF_GOLD) - Number(obj.STAFF_GOLD);
            });
             
            this.details(data);
            this.changeHighChartM(data);  
        },

        details : function(data) {

            var arr = [];
                arr.push({name:'Date',val:'FMT_DATE',title:'date'});
                arr.push({name:'Total Gold',val:'TOTAL_GOLD',sum:true,title:'Total new gold'});
                arr.push({name:'Man',val:'MALE_AMOUNT',title:'Male gold members'});
                arr.push({name:'Woman',val:'FEMALE_AMOUNT',title:'Female gold members'});
                arr.push({name:'P-6',val:'PLAN_MONTHS_SIX',title:'Paid 6 months'});
                arr.push({name:'P-3',val:'PLAN_MONTHS_THREE',title:'Paid 3 months'});
                arr.push({name:'P-1',val:'PLAN_MONTHS_ONE',title:'Paid 1 months'});
                arr.push({name:'W/C',val:'CCARD_GOLD',sum:true,title:'Credit Card'});
                arr.push({name:'AF',val:'AF_GOLD',title:'Total gold members from affiliate'});
                arr.push({name:'Staff',val:'STAFF_GOLD',title:'Total gold members from staff'});
                arr.push({name:'Main',val:'MAIN_GOLD',title:'Total gold members from main site only'});
                arr.push({name:'Cur Gold',val:'ALL_CURRENT_MEMBERS',title:'Total number of people with gold member status'});
                arr.push({name:'Non google',val:'EXCEPT_GOOGLE_GOOLD',sum:true,title:'Nongoogle'});

            var SUM = {};
                SUM.TOTAL_GOLD = 0;
                SUM.CCARD_GOLD = 0;
                SUM.EXCEPT_GOOGLE_GOOLD = 0;
                _.each(data,function(obj){
                     SUM.TOTAL_GOLD += Number(obj.TOTAL_GOLD);
                     SUM.CCARD_GOLD += Number(obj.CCARD_GOLD);
                     SUM.EXCEPT_GOOGLE_GOOLD += Number(obj.EXCEPT_GOOGLE_GOOLD);
                }); 


            data = _.clone(data).reverse();
            //console.log(SUM);
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data,arr:arr,sum:SUM}));

        },

        changeHighChartM : function(arr) {
               
            var xAxis = highchartM.get('xAxis'),
                yAxis = highchartM.get('yAxis'),
                tooltip = highchartM.get('tooltip');
                series = highchartM.get('series'),
                chart = highchartM.get('chart'),
                title = highchartM.get('title'),
                plotOptions = highchartM.get('plotOptions');

                plotOptions = {};
                title = {text : 'Total Gold'}; 
                chart = {type : 'line',width:$('#index_right').width()}; 
                xAxis = {categories : _.pluck(arr,'DATE')}; 
                yAxis = {};
                tooltip = {};

                series =  [{
                      name: 'Gold',
                      color: '#FF0000',
                      data: _.map(_.pluck(arr,'TOTAL_GOLD'),function(num){return parseInt(num)}),
                      dataLabels: {
                          enabled: arr.length < share.dataLabelNum ? true : false
                      }
                }];

                highchartM.set('tooltip',tooltip);
                highchartM.set('plotOptions',plotOptions); 
                highchartM.set('title',title); 
                highchartM.set('xAxis',xAxis); 
                highchartM.set('series',series);
                highchartM.set('chart',chart);
                this.renderHighChart();     
        }, 

        renderHighChart : function() {
             var height = share.getGraphHeight(tempOpt); 
             $('#'+mId+'_graph').height(height+'px').highcharts(highchartM.attributes);
        }


    });
	module.exports = TotalGoldView;
});
